<template>
  <div 
    class="editable-div"
    contenteditable="true"
    @input="handleInput"
    @focus="saveCursorPosition"
    @blur="saveCursorPosition"
    ref="editable"
    :style="{
      minHeight: '100px',
      padding: '10px',
      border: '1px solid #ddd',
      borderRadius: '4px'
    }"
  ></div>
</template>

<script>
export default {
  name: 'EditableDiv',
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // 保存光标位置
      cursorPosition: null
    }
  },
  watch: {
    // 当父组件修改value时同步到DOM
    value(newVal, oldVal) {
      if (newVal !== oldVal && this.$refs.editable.textContent !== newVal) {
        this.saveCursorPosition();
        this.$refs.editable.textContent = newVal;
        this.$nextTick(() => {
          this.restoreCursorPosition();
        });
      }
    }
  },
  mounted() {
    // 初始化内容
    this.$refs.editable.textContent = this.value;
    // 初始光标位置在末尾
    this.moveCursorToEnd();
  },
  methods: {
    // 处理输入事件，同步到父组件
    handleInput() {
      const currentContent = this.$refs.editable.textContent;
      this.$emit('input', currentContent);
    },
    
    // 保存当前光标位置
    saveCursorPosition() {
      const selection = window.getSelection();
      if (selection.rangeCount > 0) {
        const range = selection.getRangeAt(0);
        // 计算光标在文本中的偏移量
        const container = range.startContainer;
        const offset = range.startOffset;
        
        // 保存光标位置信息
        this.cursorPosition = {
          container,
          offset,
          // 备份文本内容用于恢复时参考
          content: this.$refs.editable.textContent
        };
      }
    },
    
    // 恢复光标位置
    restoreCursorPosition() {
      if (!this.cursorPosition) {
        this.moveCursorToEnd();
        return;
      }
      
      const selection = window.getSelection();
      const range = document.createRange();
      
      try {
        // 尝试使用保存的容器恢复
        range.setStart(this.cursorPosition.container, this.cursorPosition.offset);
        range.collapse(true);
        selection.removeAllRanges();
        selection.addRange(range);
      } catch (e) {
        // 如果恢复失败（内容变化太大），则将光标移到末尾
        this.moveCursorToEnd();
      }
    },
    
    // 将光标移动到内容末尾
    moveCursorToEnd() {
      const el = this.$refs.editable;
      const range = document.createRange();
      range.selectNodeContents(el);
      range.collapse(false); // false表示光标在内容末尾
      const selection = window.getSelection();
      selection.removeAllRanges();
      selection.addRange(range);
    }
  }
}
</script>

<style scoped>
.editable-div {
  outline: none;
  white-space: pre-wrap; /* 保留换行和空格 */
  word-break: break-all;
  overflow-wrap: break-word;
}

.editable-div:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}
</style>
    